package com.jeomo.mem.starter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jeomo.base.starter.service.impl.BaseServiceImpl;
import com.jeomo.common.core.constant.SearchParam;
import com.jeomo.common.core.constant.Sort;
import com.jeomo.common.core.constant.SystemConst;
import com.jeomo.common.core.dto.PageQueryDto;
import com.jeomo.common.core.dto.PageResponseDto;
import com.jeomo.common.core.util.StringUtils;
import com.jeomo.common.util.DoubleUtil;
import com.jeomo.masterdata.starter.entity.Goods;
import com.jeomo.masterdata.starter.enums.UseScopeEnum;
import com.jeomo.masterdata.starter.mapper.GoodsMapper;
import com.jeomo.masterdata.starter.service.ILevelService;
import com.jeomo.masterdata.starter.service.IMerchantService;
import com.jeomo.mem.starter.dto.MemberSuppleDto;
import com.jeomo.mem.starter.entity.*;
import com.jeomo.mem.starter.mapper.*;
import com.jeomo.mem.starter.service.*;
import com.jeomo.mem.starter.sysoption.PointsValiditySysOption;
import com.jeomo.shiro.util.LoginSessionUtil;
import com.jeomo.shiro.util.OrgUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;

/**
 * 会员积分补录
 *
 * @author:Jackpot
 * @create 2020-10-14 11:58
 * @description:
 */
@Service
@Transactional
public class MemPointsSupplementServiceImpl extends BaseServiceImpl<MemberPointsSuppleMapper, MemberPointsSupplement>
        implements IMemPointsSupplementService {

    private final String ORDER_NO = "order_no";
    private final String MERCHANT = "merchant";
    private final String PAY_TIME = "pay_time";
    private final String WORKFLOW_STATUS = "workflow_status";
    private final String MEMBER_CARD = "member_card";
    private final String MEMBER_PHONE = "member_phone";

    private final String P_CODE = "p_code";
    private final String HANDLE_TIME = "handle_time";
    @Resource
    private MemberPointsSuppleMapper memberPointsSuppleMapper;
    @Resource
    private MemberPointsSuppleDetailMapper memberPointsSuppleDetailMapper;
    @Resource
    GoodsMapper goodsMapper;
    @Resource
    IMerchantService merchantService;
    @Resource
    ILevelService levelService;
    @Resource
    IMemberPointsService memberPointsService;
    @Resource
    IMemberPointsRuleService memberPointsRuleService;
    @Resource
    MemberPointsRuleExeMapper memberPointsRuleExeMapper;
    @Resource
    MemberPointsRuleMapper memberPointsRuleMapper;
    @Resource
    private PointsValiditySysOption pointsValiditySysOption;

    //
    @Resource
    IMemPointsActivityRuleService memPointsActivityRuleService;
    @Resource
    private MemberPointsActivityRuleMapper memberActivityRuleMapper;
    @Resource
    private IMemPointsActivityInfoService memPointsActivityInfoService;


    @Override
    public PageResponseDto pageSearch(PageQueryDto dt) {
        String currOrg = OrgUtil.getCurrOrg();
        Map<String, Object> searchParams = dt.getSearchParams();
        if (searchParams != null) {
            Map<String, Object> params = new HashMap<>();
            params.put(SearchParam.SEARCH_EQ + SystemConst.ORG, currOrg);
            params.put(SearchParam.SEARCH_EQ + ORDER_NO, searchParams.get(ORDER_NO));
            params.put(SearchParam.SEARCH_EQ + MERCHANT, searchParams.get(MERCHANT));
            params.put(SearchParam.SEARCH_EQ + PAY_TIME, searchParams.get(PAY_TIME));
            params.put(SearchParam.SEARCH_EQ + WORKFLOW_STATUS, searchParams.get(WORKFLOW_STATUS));
            params.put(SearchParam.SEARCH_EQ + MEMBER_CARD, searchParams.get(MEMBER_CARD));
            params.put(SearchParam.SEARCH_EQ + MEMBER_PHONE, searchParams.get(MEMBER_PHONE));
            dt.setSearchParams(params);
        }
        Map<String, String> sort = new HashMap<>(8);
        sort.put(HANDLE_TIME, Sort.DESC);
        dt.setSorts(sort);
        PageResponseDto pageResponseDto = super.pageSearch(dt);

        Map<String, String> levelMap = levelService.queryCache();
        Map<String, String> merchantMap = merchantService.queryCache();
        List<?> items = pageResponseDto.getItems();
        for (Object item : items) {
            MemberPointsSupplement memberPointsRule = (MemberPointsSupplement) item;
            patchData(levelMap, merchantMap, memberPointsRule);
        }
        return pageResponseDto;
    }

    /**
     * 补全数据
     *
     * @param levelMap
     * @param merchantMap
     * @param memberPointsRule
     */
    public void patchData(Map<String, String> levelMap, Map<String, String> merchantMap, MemberPointsSupplement memberPointsRule) {
        if (memberPointsRule == null) return;
        memberPointsRule.setMerchantName(merchantMap.get(memberPointsRule.getMerchant()));
        Object levelCode = levelMap.get(memberPointsRule.getMemberLevel());
        if (levelCode != null) {
            memberPointsRule.setMemberLevelName(levelCode.toString());
        }
    }

    /**
     * 补全明细数据
     *
     * @param memberRuleList
     */
    public void patchDetailData(List<MemberPointsSuppleDetail> memberRuleList) {
        Map<Object, Object> cacheMap = memPointsActivityInfoService.queryCache();
        for (MemberPointsSuppleDetail suppleDetail : memberRuleList) {

            String goodsCode = suppleDetail.getGoodsCode();
            Goods goods = goodsMapper.selectById(goodsCode);
            suppleDetail.setGoodsName(goods.getName());

            MemberPointsRule memberPointsRule = memberPointsRuleMapper.selectById(suppleDetail.getRule());
            if (memberPointsRule != null) {
                suppleDetail.setRuleName(memberPointsRule.getName());
            }

//            String activities = suppleDetail.getActivities();
//            if (StringUtils.isEmpty(activities)) continue;
//            String[] activityCodeArray = StringUtils.strToArray(activities);
//            String[] activityNameArray = new String[activityCodeArray.length];
//            for (int i = 0; i < activityCodeArray.length; i++) {
//                MemberPointsActivityRule memberPointsActivityRule = memberActivityRuleMapper.selectById(activityCodeArray[i]);
//                if (memberPointsActivityRule == null) continue;
//                Object activityName = cacheMap.get(memberPointsActivityRule.getActivityCode());
//                activityNameArray[i] = activityName != null ? activityName.toString() : "";
//            }
//            suppleDetail.setActivitiesCode(activityCodeArray);
//            suppleDetail.setActivitiesName(activityNameArray);
        }
    }

    @Override
    public MemberSuppleDto getMemberPointSupple(String code) {

        Map<String, String> levelMap = levelService.queryCache();
        Map<String, String> merchantMap = merchantService.queryCache();

        MemberPointsSupplement memberRule = memberPointsSuppleMapper.selectById(code);
        patchData(levelMap, merchantMap, memberRule);
        QueryWrapper<MemberPointsSuppleDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(P_CODE, code);
        List<MemberPointsSuppleDetail> memberRuleList = memberPointsSuppleDetailMapper.selectList(queryWrapper);
        patchDetailData(memberRuleList);
        MemberSuppleDto memberActivityDto = new MemberSuppleDto();
        memberActivityDto.setMemberPointsSupplement(memberRule);
        memberActivityDto.setMemberPointsSuppleDetails(memberRuleList);
        return memberActivityDto;
    }

    @Override
    public int updateWorkflowStatus(String code, String auditor, int status) {
        return this.getBaseMapper().updateWorkflowStatus(code, LocalDateTime.now(), auditor, status);
    }

    @Override
    public List<MemberPointsSuppleDetail> queryGoodsConsumerInfo(Date date, String levelCode, String merchant, double amount) {

        if (merchant == null || merchant.isEmpty() || amount == 0D) return null;

        List<Goods> goodsList = goodsMapper.queryGoodsByMerchant(merchant);
        if (goodsList == null || goodsList.isEmpty()) return null;
        Goods goods = goodsList.get(0); //默认取商户下的第一个商品
        List<MemberPointsSuppleDetail> goodsConsumers = new ArrayList<>();
        MemberPointsSuppleDetail memberPointsSuppleDetail = new MemberPointsSuppleDetail();
        String goodsCode = goods.getCode();
        String goodsName = goods.getName();
        memberPointsSuppleDetail.setGoodsCode(goodsCode);
        memberPointsSuppleDetail.setGoodsName(goodsName);
        memberPointsSuppleDetail.setNumber(1);
        memberPointsSuppleDetail.setPrice(amount);
        memberPointsSuppleDetail.setAmount(amount);
        goodsConsumers.add(memberPointsSuppleDetail);
        //查询积分详情
        MemberPointsRuleExe pointsRule = memberPointsService.getPointsRuleByGoods(levelCode, goodsCode);
        if (pointsRule == null) return goodsConsumers;
        int basePoints = memberPointsService.getPoints(levelCode, goodsCode, amount, UseScopeEnum.GOODS);
        int points = basePoints;//基础积分
        String ruleCode = pointsRule.getRuleCode();
        String rule = pointsRule.getRuleCode();

        memberPointsSuppleDetail.setRule(ruleCode);
        memberPointsSuppleDetail.setRuleName(rule);
        memberPointsSuppleDetail.setPointsBasic(points);
        //设置积分过期时间
        MemberPointsRule memberPointsRule = memberPointsRuleMapper.selectById(ruleCode);
        LocalDate expiredTime = pointsValiditySysOption.getValidityDate(LocalDate.now());
        memberPointsSuppleDetail.setExpiredTime(expiredTime);
        //查询积分活动详情
        Map<String, MemberPointsActivityExe> activities = memPointsActivityRuleService.getActivities(levelCode, goodsCode, amount, date);
        List<MemberPointsActivityExe> activityExeList = new ArrayList<>(activities.values());
        int activitySize = activityExeList.size();
        if (activitySize <= 0) return goodsConsumers;

        double activityPoints = 0;//活动赠送积分
        String[] activityCodeArray = new String[activitySize];
        String[] activityNameArray = new String[activitySize];
        for (int i = 0; i < activitySize; i++) {
            MemberPointsActivityExe activityExe = activityExeList.get(i);
            activityCodeArray[i] = activityExe.getRuleCode();
            activityNameArray[i] = activityExe.getActivityName();

            Double addRatio = activityExe.getAddRatio();
            Double multiRatio = activityExe.getMultiRatio();
            double resultPoints = DoubleUtil.add(DoubleUtil.mul(basePoints, multiRatio), addRatio);
            double extraPoints = DoubleUtil.sub(resultPoints, basePoints);
            activityPoints = DoubleUtil.add(activityPoints, extraPoints);
        }
//        memberPointsSuppleDetail.setActivities(StringUtils.arrayToStr(activityCodeArray));
//        memberPointsSuppleDetail.setActivitiesCode(activityCodeArray);
//        memberPointsSuppleDetail.setActivitiesName(activityNameArray);
//        memberPointsSuppleDetail.setPointsActivity((int) activityPoints);
        double totalPoints = DoubleUtil.add(activityPoints, basePoints);//本次获得的总积分合计
        memberPointsSuppleDetail.setPointsTotal((int) totalPoints);
        return goodsConsumers;
    }

    @Override
    public int queryToDoPhotographIntegral() {
        return memberPointsSuppleMapper.queryToDoPhotographIntegral(LoginSessionUtil.getCurrentLoginInfo().getOrgCode());
    }
}
